<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />

    <!-- <div>地图</div> -->
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    ></r-table>
    <!--    <r-form :formRules="formRules" :formHandle="formHandle" :formData="formData" :formCols="formCols" ref="elForm" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />-->

    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules2"
      :formCols="formCols2"
      :formHandle="formHandle2"
      :formData="formData2"
      ref="elForm2"
      :inline="false"
      dialogWidth="850px"
    >
      <!-- 点击Edit按钮出现的Template，里面的站点地址 -->
      <!-- 省 -->
      <div class="zhandiandiz" v-if="isshowss">
        <span>省/市/区/街</span>
        <el-select
          v-model="sValue"
          placeholder="Please Select省份"
          @change="sZhandiandizhi($event)"
          class="szddz"
        >
          <el-option
            v-for="item in sOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 市 -->
        <el-select
          v-model="cValue"
          placeholder="Please Select城市"
          @change="cZhandiandizhi($event)"
          class="czddz"
        >
          <el-option
            v-for="item in cOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 区 -->
        <el-select
          v-model="qValue"
          placeholder="Please Select区/县"
          @change="qZhandiandizhi($event)"
          class="qzddz"
        >
          <el-option
            v-for="(item, index) in qOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 街 -->
        <el-select
          v-model="jValue"
          placeholder="Please Select街道"
          @change="jZhandiandizhi($event)"
          class="jzddz"
        >
          <el-option
            v-for="(item, index) in jOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="
            border: 1px solid #c0c0c0;
            width: 150px;
            height: auto;
            display: none;
          "
        ></div>
        <p>
          点击地图确认坐标 经度：{{ formData2.lng }} 纬度：{{ formData2.lat }}
          <!-- *可以Pass点击地图，快速找到站点地址 -->
        </p>
        <div id="l-map"></div>
      </div>
    </r-form>

    <warehouse_gate
      :res="warehouse_gate_data"
      v-if="warehouse_gate_data.show"
      v-on:warehouse_gate_dall="warehouse_gate_dall"
    ></warehouse_gate>

    <Abnormal_record ref="Abnormal_record"></Abnormal_record>

    <useDetailDialog
      :visible.sync="visible"
      :useDetail="useDetail"
    ></useDetailDialog>
  </div>
</template>
<script>
import warehouse_gate from "./cus/warehouse_gate";
import Abnormal_record from "./cus/Abnormal_record";
import baidumap from "../js/baidumap";
import useDetailDialog from "./cus/useDetailDialog.vue";
export default {
  components: {
    warehouse_gate,
    Abnormal_record,
    useDetailDialog
  },
  data() {
    const checkAge = (rule, value, callback) => {
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("Please Input数字值"));
        } else {
          if (value < 0) {
            callback(new Error("不能小于0"));
          } else {
            callback();
          }
        }
      }, 200);
    };
    return {
      // checkboxGroup: "",
      pt: "116.331398, 39.897445",
      isshowss: false, //Control省市区街显示隐藏
      sValue: "", //Edit页面 站点地址 选项的值(省)
      sLabel: "", //Edit页面 站点地址 选项的键名(省)
      sJingwei: "", //Edit页面 站点地址 选项的经纬度(省)
      sOption: [], //Edit页面 站点地址 Data源(省)
      cValue: "", //Edit页面 站点地址 选项的值(市)
      cLabel: "", //Edit页面 站点地址 选项的键名(市)
      cJingwei: "", //Edit页面 站点地址 选项的经纬度(市)
      cOption: [], //Edit页面 站点地址 Data源(市)
      qValue: "", //Edit页面 站点地址 选项的值(区)
      qLabel: "", //Edit页面 站点地址 选项的键名(区)
      qJingwei: "", //Edit页面 站点地址 选项的经纬度(区)
      qOption: [], //Edit页面 站点地址 Data源(区)
      jValue: "", //Edit页面 站点地址 选项的值(街道)
      jLabel: "", //Edit页面 站点地址 选项的键名(街道)
      jJingwei: "", //Edit页面 站点地址 选项的经纬度(街道)
      jOption: [], //Edit页面 站点地址 Data源(街道)
      userType: "", //反映是Agent还是Operator
      visible: false,
      useDetail: {
        deviceType: "3",
        deviceNo: "",
        deviceStatus: "",
        totalMoney: 0,
        totalOrder: 0,
        serverTime: 0,
        engaged: []
      },

      baiduMap: null,
      warehouse_gate_data: {
        id: "",
        show: false
      },
      searchData: {
        deviceName: "",
        sn: "",
        deviceStatus: "",
        operatorId: "",
        agentId: "",
        distStatus: "",
        commonType: "",
        deviceType: 3,
        siteId: ""
      },
      // Search栏信息
      searchForm: [
        {
          type: "input",
          prop: "sn",
          placeholder: "Device Number"
          // width: 150
        },
        {
          type: "select",
          prop: "siteId",
          placeholder: "铺设站点",
          width: 150,
          options: []
        },
        {
          type: "input",
          prop: "deviceName",
          placeholder: "Device Name"
          // width: 150
        },
        {
          type: "select",
          prop: "operatorId",
          placeholder: "所属Operator",
          options: [],
          // width: 150,
          isShow: () => {
            return sessionStorage.role == "platform" ? true : false;
          }
        },
        {
          type: "select",
          prop: "agentId",
          placeholder: "Belonging Agent商",
          options: [],
          // width: 150,
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          type: "select",
          prop: "distStatus",
          placeholder: "是否分配",
          // width: 150,
          options: [
            { label: "未分发", value: "0" },
            { label: "已分发", value: "1" }
          ]
        },
        {
          type: "select",
          prop: "commonType",
          placeholder: "PublicType",
          // width: 150,
          options: [
            { label: "Public", value: "1" },
            { label: "Private", value: "2" }
          ]
        }
        // {
        //   type: 'select',
        //   prop: 'name',
        //   placeholder: '设备Type',
        //   width: 150,
        //   options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'Charging Cabinet',value:'3'},
        //   ]
        // },
      ],
      // Search按钮
      searchHandle: [
        {
          label: "Search",
          type: "success",
          icon: "el-icon-search",
          handle: e => this.init()
        }
      ],
      //  Add设备按钮
      tableHandles: [
        // {
        //   label: "关联广告合集",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        // {
        //   label: "关联Package",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        {
          label: "Add设备",
          type: "primary",
          handle: e => {
            this.formData2.id = null;
            if (this.userType == "Agent") {
              this.isshowss = true;
            } else {
              this.isshowss = false;
            }

            this.add();
          }
        }
        // {
        //   label: "11",
        //   type: "primary",
        //   handle: async () => {
        //     const res = await this.apis.importTemplate();

        //     location.href = process.env.VUE_APP_URL + res.msg;
        //   },
        // },
      ],
      tableData: [],
      //表格信息

      tableCols: [
        {
          label: "Device Number",
          prop: "sn"
        },
        {
          label: "QR Code",
          type: "image",
          width: 100,
          prop: "qrCode"
        },
        {
          label: "Device Name",
          prop: "deviceName"
        },
        {
          label: "铺设站点",
          prop: "name" //siteId name
          // options:[]
        },
        {
          label: "Current定位",
          prop: "address"
        },
        {
          label: "Charging CabinetPackage",
          prop: "mealName", //mealId
          width: 100,

          isShow: e => this.userType == "Agent"
        },
        {
          label: "Belonging Agent商",
          prop: "agentName",
          // options:[],
          width: 100
        },
        // {
        //   label: "设备所属",
        //   prop: "operatorName",
        // },
        {
          label: "Maintenance Personnel",
          prop: "merName"
        },
        {
          label: "广告合集",
          prop: "advertList"
        },
        {
          label: "电量表",
          prop: "usedElectric"
        },
        {
          label: "设备Status",
          prop: "deviceStatus",
          formatter: e => {
            if (e.deviceStatus == 1) {
              return "(Online)运行中";
            } else if (e.deviceStatus == 2) {
              return "Offline";
            } else if (e.deviceStatus == 3) {
              return "设备故障";
            } else if (e.deviceStatus == 0) {
              return "-";
            }
          }
        },
        {
          label: "Update Time",
          prop: "lastTime"
        },
        {
          label: "EnableStatus",
          type: "switch",
          prop: "useStatus",
          values: [1, 2],
          change: row => this.changestate(row)
        },
        {
          label: "Operations",
          type: "button",
          width: 220,
          btnList: [
            {
              label: "EmployDetails",
              type: "text",
              handle: async row => {
                this.useDetail.deviceNo = row.deviceNo;
                this.useDetail.deviceStatus = row.deviceStatus;
                const res = await this.apis.cabinet_detailList(row.id, "3");
                // console.log("res----", res);
                const data = res.data.extend;
                this.useDetail.serverTime = data.serverTime;
                this.useDetail.totalMoney = data.totalMoney;
                this.useDetail.totalOrder = data.totalOrder;
                // data.engaged.map((item) => {
                //   item.checked = false;
                //   return item;
                // });
                this.useDetail.engaged = data.engaged;
                this.visible = true;
              }
            },
            {
              label: "查看仓门",
              type: "text",
              handle: row => {
                this.warehouse_gate_data.id = row.id;
                this.warehouse_gate_data.show = true;
              }
            },
            {
              label: "异常Record",
              type: "text",
              handle: row => {
                this.$refs.Abnormal_record.show_fun(row);
              }
            },
            {
              label: "EmployRecord",
              type: "text",
              isShow: () => {
                const role = sessionStorage.role;
                return role == "operator" || role == "agent" ? true : false;
              },
              handle: row => {
                this.$router.push({
                  path: "/device_management-Charging_record",
                  query: {
                    deviceNo: row.deviceNo
                  }
                });
              }
            },
            {
              label: "Edit",
              type: "text",
              handle: row => {
                this.isshowss = false;
                this.add(row);
              }
            },
            {
              label: "Delete",
              type: "text",
              handle: async row => {
                this.$confirm("确定要Delete吗?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    var res = await this.apis.device_del({
                      id: row.id
                    });
                    this.$message({
                      type: "success",
                      message: "DeleteSuccess!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },

      // formData: {
      //   name: "",
      //   money: "",
      //   giftMoney: "",
      //   status: ""
      // },
      // formCols: [
      //   { type: "input", label: "Package Name", width: 350, prop: "name" },
      //   { type: "input", label: "PackageMoney", width: 350, prop: "money", remark: '元' },
      //   { type: "input", label: "Gift Amount", width: 350, prop: "giftMoney", remark: '元' },
      //   { type: "switch", label: "上线/下线", width: 350, prop: "status" },
      // ],
      // formRules: {
      //   name: [
      //     { required: true, message: 'Please InputPackage Name', trigger: 'blur' },
      //   ],
      //   money: [
      //     { required: true, message: 'Please InputPackageMoney', trigger: 'blur' },
      //   ],
      //   giftMoney: [
      //     { required: true, message: 'Please InputPackageMoney', trigger: 'blur' },
      //   ],
      // },
      // formHandle: [
      //   {
      //     label: "Cancel",
      //     handle: e => this.elFormVisible(),
      //   },
      //   {
      //     label: "Confirm",
      //     type: "success",
      //     handle: e => this.elFormSubmit(),
      //   },
      //
      // ],

      formData2: {
        deviceNo: "",
        deviceName: "",
        address: "",
        siteId: "",
        // name: '',
        lng: "",
        lat: "",
        operatorId: "",
        agentId: "",
        merId: "",
        // boxNum: '',
        cols: "",
        rows: "",
        sim: "",
        deviceType: "3",
        mealId: ""
        // mealName: '',
      },
      formCols2: [
        {
          type: "input",
          label: "Device Number",
          placeholder: "Please Enter",
          width: 350,
          prop: "deviceNo"
        },
        {
          type: "input",
          label: "Device Name",
          placeholder: "Please Enter",
          width: 350,
          prop: "deviceName"
        },
        // { type: 'input', label: '格子数量', placeholder: 'Please Enter', width: 350, prop: 'boxNum' },
        {
          type: "input",
          label: "列数",
          placeholder: "Please Enter",
          width: 350,
          prop: "cols",
          isDisabled: e => (e.id ? true : false)
        },
        {
          type: "input",
          label: "行数",
          placeholder: "Please Enter",
          width: 350,
          prop: "rows",
          isDisabled: e => (e.id ? true : false)
        },
        {
          type: "input",
          label: "sim 编号",
          placeholder: "Please Enter",
          width: 350,
          prop: "sim"
        },
        // { type: "select", label: "设备Type", placeholder: 'Please Enter', width: 350, prop: "deviceType",options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'Charging Cabinet',value:'3'},
        //   ] },
        {
          type: "select",
          label: "选择站点",
          placeholder: "Please Enter",
          width: 350,
          prop: "siteId",
          options: []
        },
        {
          type: "select",
          label: "选择Operator",
          placeholder: "Please Enter",
          width: 350,
          prop: "operatorId",
          options: [],
          isShow: () => {
            return sessionStorage.role == "platform" ? true : false;
          }
        },
        {
          type: "select",
          label: "选择Agent",
          placeholder: "Please Enter",
          width: 350,
          prop: "agentId",
          options: []
          // isShow: () => {//operator是Agent
          //   return sessionStorage.role == "operator" ? true : false;
          // },
        },
        {
          type: "select",
          label: "Select Maintenance",
          placeholder: "Please Enter",
          width: 350,
          prop: "merId",
          options: [],
          isShow: () => {
            //operator是Agent
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          type: "select",
          label: "关联Package",
          placeholder: "Please Enter",
          width: 350,
          prop: "mealId",
          isShow: () => {
            return this.userType == "Operator" ? false : true;
          }
        },
        {
          //只有Add才有省市区街四级联动，Edit没有
          type: "",
          isShow: () => {
            return !this.formData2.id && this.userType == "Agent"
              ? true
              : false;
          }
        },

        {
          type: "input",
          id: "suggestId",
          label: "站点地址",
          width: 350,
          prop: "address",
          isShow: () => {
            return this.userType == "Operator" ? false : true;
          }
        },
        {
          type: "slot",
          name: "slot3",
          label: "",
          prop: "lng",
          isShow: () => {
            return this.userType == "Operator" ? false : true;
          }
        }
      ],
      formRules2: {
        deviceNo: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        // boxNum: [{ required: true, message: 'Please Enter', trigger: 'blur' }, { validator: checkAge, trigger: 'blur' }],
        cols: [
          { required: true, message: "Please Enter", trigger: "blur" },
          { validator: checkAge, trigger: "blur" }
        ],
        rows: [
          { required: true, message: "Please Enter", trigger: "blur" },
          { validator: checkAge, trigger: "blur" }
        ],
        sim: [{ required: true, message: "Please Enter", trigger: "blur" }],
        // deviceType: [{ required: true, message: "Please Select", trigger: "blur" }],
        siteId: [
          { required: true, message: "Please Select站点", trigger: "blur" }
        ],
        mealId: [
          { required: true, message: "Please InputPackage", trigger: "blur" }
        ],
        operatorId: [
          { required: true, message: "Please SelectOperator", trigger: "blur" }
        ],
        agentId: [
          { required: true, message: "Please SelectAgent", trigger: "blur" }
        ],
        merId: [
          {
            required: true,
            message: "Please SelectMaintenance",
            trigger: "blur"
          }
        ],
        lng: [
          { required: true, message: "请点击地图选择经纬度", trigger: "blur" }
        ],

        address: [
          { required: true, message: "Please Input详细地址", trigger: "blur" }
        ]
      },
      formHandle2: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible("", "elForm2")
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ]
    };
  },
  computed: {},
  mounted() {
    console.log(sessionStorage.nickName);
    console.log(sessionStorage.optUserId);
    this.init();
    this.site_list();
    //userType为1是Operator，2是Agent
    if (sessionStorage.getItem("userType") == "1") {
      this.userType = "Operator";
    }
    if (sessionStorage.getItem("userType") == "2") {
      this.userType = "Agent";
    }

    if (sessionStorage.role == "platform") {
      this.operator_list();
    }
    if (sessionStorage.role == "operator") {
      this.agent_list();
      this.maintenancer_list();
    }
    if (sessionStorage.role !== "operator") {
      this.agent_list();
    }

    this.mealExchange_list();
  },
  watch: {
    // 监听省，如果下拉框的省发生改变，就会发送请求，更新市的Data
    sLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用Edit页面 --站点地址-- 城市（Data） 的方法
        this.czhandianfangfa(this.sLabel, this.sValue);
        // 当重新选择省，市区街和站点地址情况，重新更新
        this.cLabel = "";
        this.qLabel = "";
        this.jLabel = "";
        this.cValue = "";
        this.qValue = "";
        this.jValue = "";
      }
    },
    // 监听市，如果下拉框的市发生改变，就会发送请求，更新区的Data
    cLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用Edit页面 --站点地址-- 区（Data） 的方法
        this.qzhandianfangfa(this.cLabel, this.cValue);
        // 当重新选择市，区街和站点地址情况，重新更新
        this.qLabel = "";
        this.jLabel = "";
        this.qValue = "";
        this.jValue = "";
      }
    },
    // 监听区，如果下拉框的区发生改变，就会发送请求，更新街道的Data
    qLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用Edit页面 --站点地址-- 街道（Data） 的方法
        this.jzhandianfangfa(this.qLabel, this.qValue);
        // 当重新选择区，街和站点地址情况，重新更新

        this.jLabel = "";
        this.jValue = "";
      }
    },
    // 监听街道，如果下拉框的街道发生改变，就会发送请求，更新街道的Data
    // jValue(newV, oldV) {
    //   if (newV !== oldV) {
    //     console.log(newV, oldV);
    //     // 调用Edit页面 --站点地址-- 街道（Data） 的方法
    //     // this.jzhandianfangfa(this.qLabel, this.qValue)
    //   }
    // },
    lng(newV, oldV) {
      if (newV !== oldV) {
        console.log(newV, oldV, "===============");
      }
    }
  },
  updated() {
    // 选择省市区街下拉框，Edit页面的站点地址会改变
    if (this.sLabel && !this.cLabel && !this.qLabel && !this.jLabel) {
      this.formData2.address = "";
      this.formData2.address = this.sLabel;
    } else if (this.sLabel && this.cLabel && !this.qLabel && !this.jLabel) {
      this.formData2.address = "";
      this.formData2.address = this.sLabel + this.cLabel;
    } else if (this.sLabel && this.cLabel && this.qLabel && !this.jLabel) {
      this.formData2.address = "";
      this.formData2.address = this.sLabel + this.cLabel + this.qLabel;
    } else if (this.sLabel && this.cLabel && this.qLabel && this.jLabel) {
      this.formData2.address = "";
      this.formData2.address =
        this.sLabel + this.cLabel + this.qLabel + this.jLabel;
    } else {
    }
  },
  methods: {
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.device_list(parm);
      if (res) {
        let key = "mealName";
        let keys = "name";
        this.tableData = res.rows;
        this.tablePage.total = res.total;
        this.tableData.forEach(item => {
          // 防止Add的属性值为空
          if (item.mealChargeEntity) {
            item[key] = item.mealChargeEntity.mealName;
          } else {
            item[key] = "-";
          }
          // 防止Add的属性值为空
          if (item.siteEntity) {
            item[keys] = item.siteEntity.name;
          } else {
            item[keys] = "-";
          }
        });
      }
      // Edit页面 站点地址  ---拿到省份(Data)
      const addressRes = await this.apis.allAddressList({});
      if (addressRes.code === 0) {
        var array = new Array();
        addressRes.result.forEach(item => {
          let obj = {
            label: item.name,
            value: item.adcode,
            jingwei: item.center
          };
          this.sOption.push(obj);
          array.push(obj);
        });

        this.formCols2[
          this.labIndex2(this.formCols2, "address")
        ].options = array;
      }
    },
    async elFormSubmit() {
      this.$refs.elForm2.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData2.id) {
            let res = await this.apis.device_updata(this.formData2);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          } else {
            let res = await this.apis.device_save(this.formData2);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          }
        }
      });
    },
    async changestate(row) {
      let res = await this.apis.device_updata({
        id: row.id,
        useStatus: row.useStatus
      });

      this.$message({
        message: "OperationsSuccess！",
        type: "success"
      });
    },
    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });

      this.formData.status = row["state"] == 1 ? true : false;
      this.formData.id = row.id;
      // if (this.formCols[1].label == '登录密码') {
      //     this.formCols.splice(1, 1)
      // }

      this.elFormVisible();
    },
    map() {
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder();
      map.addEventListener("click", function(e) {
        that.formData2.lng = e.point.lng;
        that.formData2.lat = e.point.lat;
        var pt = e.point;
        geoc.getLocation(pt, function(rs) {
          that.formData2.address = rs.address; //点击地图拿到详细地址
          var addComp = rs.addressComponents;
          // that.formData.city = addComp.city;
          // alert(
          //   addComp.province +
          //     ", " +
          //     addComp.city +
          //     ", " +
          //     addComp.district +
          //     ", " +
          //     addComp.street +
          //     ", " +
          //     addComp.streetNumber
          // );
        });
      });
      map.enableScrollWheelZoom(); //Enable滚轮放大缩小，默认Forbidden
      map.enableContinuousZoom(); //Enable地图惯性拖拽，默认Forbidden
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 10);
      });
    },
    add(row) {
      if (row) {
        this.formData2.id = row.id;
      } else {
        this.formData2.id = null;
      }
      this.elFormVisible("", "elForm2").then(res => {
        if (this.userType == "Agent") {
          this.map().then(res => {
            if (row) {
              Object.keys(this.formData2).forEach(key => {
                this.formData2[key] = row[key];
              });
            }
          });
        } else {
          if (row) {
            Object.keys(this.formData2).forEach(key => {
              this.formData2[key] = row[key];
            });
          }
        }
      });
    },
    //站点列表
    async site_list() {
      const res = await this.apis.site_list({
        pageNum: 1,
        pageSize: 100000
      });

      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "siteId")
      ].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "siteId")
      ].options = options;
    },

    //Operator-列表
    async operator_list() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 100000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "operatorId")
      ].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "operatorId")
      ].options = options;
    },

    //Agent列表
    async agent_list() {
      const res = await this.apis.agent_list({
        pageNum: 1,
        pageSize: 100000
      });
      if (sessionStorage.role !== "operator" && res.rows.length == 0) {
        var list = [
          {
            name: sessionStorage.nickName,
            id: sessionStorage.optUserId
          }
        ];
      } else {
        var list = res.rows || [];
      }
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });
      this.searchForm[
        this.labIndex2(this.searchForm, "agentId")
      ].options = options;
      this.formCols2[
        this.labIndex2(this.formCols2, "agentId")
      ].options = options;
    },
    //Maintenance Personnel List
    async maintenancer_list() {
      const res = await this.apis.maintenancer_list({
        pageNum: 1,
        pageSize: 1000000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.userName,
          value: res.id
        });
      });

      this.formCols2[this.labIndex2(this.formCols2, "merId")].options = options;
    },

    //Package列表
    async mealExchange_list() {
      const res = await this.apis.mealCharge_list({
        pageNum: 1,
        pageSize: 1000000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.mealName,
          value: res.id
        });
      });
      this.formCols2[
        this.labIndex2(this.formCols2, "mealId")
      ].options = options;
    },

    warehouse_gate_dall() {
      this.warehouse_gate_data.show = false;
    },

    formatSeconds(value) {
      var theTime1 = parseInt(value); // 需要转换的时间分钟
      var theTime2 = 0; // 小时
      var theTime3 = 0; // 天

      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60);
        theTime1 = parseInt(theTime1 % 60);
        if (theTime2 > 24) {
          // 大于24小时
          theTime3 = parseInt(theTime2 / 24);
          theTime2 = parseInt(theTime2 % 24);
        }
      }
      var result = "";
      if (theTime1 > 0) {
        result = "" + parseInt(theTime1) + "分钟";
      }
      if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + "小时" + result;
      }
      if (theTime3 > 0) {
        result = "" + parseInt(theTime3) + "天" + result;
      }
      return result;
    },

    // // Edit页面 站点地址 的点击方法(省)
    sZhandiandizhi(value) {
      // console.log(value);
      let sObj = {};
      sObj = this.sOption.find(item => {
        //这里的sOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.sLabel = sObj.label; //拿到键名
      this.sOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.sJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.sJingwei.split(",")[0];
      this.formData2.lat = this.sJingwei.split(",")[1];
      this.pt = this.sJingwei;
    },

    // // Edit页面 站点地址 的点击方法(市)
    cZhandiandizhi(value) {
      // console.log(value);
      let cObj = {};
      cObj = this.cOption.find(item => {
        //这里的cOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.cLabel = cObj.label; //拿到键名
      this.cOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.cJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.cJingwei.split(",")[0];
      this.formData2.lat = this.cJingwei.split(",")[1];
      this.pt = this.cJingwei;
    },
    // // Edit页面 站点地址 的点击方法(区)
    qZhandiandizhi(value) {
      let qObj = {};
      qObj = this.qOption.find(item => {
        //这里的cOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.qLabel = qObj.label; //拿到键名
      this.qOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.qJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.qJingwei.split(",")[0];
      this.formData2.lat = this.qJingwei.split(",")[1];
      this.pt = this.qJingwei;
    },

    // // Edit页面 站点地址 的点击方法(街道)
    jZhandiandizhi(value) {
      let jObj = {};
      jObj = this.jOption.find(item => {
        //这里的jOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.jLabel = jObj.label; //拿到键名
      console.log(this.jLabel);
      this.jOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.jJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.jJingwei.split(",")[0];
      this.formData2.lat = this.jJingwei.split(",")[1];
      this.pt = this.jJingwei;
    },

    // // Edit页面地图 ---拿到城市（Data）
    czhandianfangfa(label, value) {
      this.cOption = []; //每次进来先清空城市的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            res.result.forEach(item => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              };
              this.cOption.push(obj);
            });
            console.log(this.cOption);
          }
        });
    },

    // // Edit页面地图 ---拿到区（Data）
    qzhandianfangfa(label, value) {
      this.qOption = []; //每次进来先清空区/县的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            res.result.forEach(item => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              };
              this.qOption.push(obj);
            });
          }
        });
    },
    // // Edit页面地图 ---拿到街道（Data）
    jzhandianfangfa(label, value) {
      this.jOption = []; //每次进来先清空街道的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            // 增加判断，如果镇下面没有街道，就直接让街道变成空
            if (res.result.length !== 0) {
              res.result.forEach(item => {
                let obj = {
                  label: item.name,
                  value: item.adcode,
                  jingwei: item.center
                };
                this.jOption.push(obj);
              });
            } else {
              this.jOption = [];
            }
          }
        });
    }
  }
};
</script>
<style scoped lang="scss">
// ControlEdit页面 站点地址的长度
.szddz {
  width: 130px;
}

.czddz {
  width: 130px;
}

.qzddz {
  width: 130px;
}

.jzddz {
  width: 130px;
}

.zhandiandiz {
  position: relative;
  // top: -351px;
  top: -405px;
  left: 70px;
}

.zhandiandiz > span {
  margin-right: 10px;
}

.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;
}

#l-map {
  height: 250px;
  width: 100%;
}

#r-result {
  width: 100%;
}
</style>
